"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/11/27
 */
import * as React from 'react'
import {autoSize, commonProps, commonStyles,} from "../../assets/styles/common";
import NavBackButton from "../../component/BackButton";
import Colors from "../../assets/styles/Colors";
import {contactList, homeDynamicList} from "../../assets/data";
import DynamicItem from "../../component/DynamicItem";
import WhiteSpace from "../../component/WhiteSpace";
import {SCREEN_HEIGHT, SCREEN_WIDTH} from "../../constant";
import {archiveStyles} from "../../assets/styles/archive";
import MyIcon from "../../component/icon";
import MyText from "../../component/MyText";
import NavRightButton from "../../component/RightButton";
import Avatar from "../../component/Avatar";
import {UserProfilePage} from "../../interface/router";
import {userProfileStyle} from "../../assets/styles/userProfile";
import Request from "../../utils/Request";

const {View, FlatList, Animated, TouchableOpacity} = require('react-native');
const {connect} = require('react-redux');
const NavigationBar = require('react-native-navbar').default;
const {Actions} = require("react-native-router-flux");
const {ActionSheet} = require('antd-mobile');

const Title = (props: { text: string }) => {
    return (
        <View style={[commonStyles.centerVH, {
            padding: 10,
            borderBottomColor: Colors.Background,
            borderBottomWidth: 1
        }]}>
            <MyText fontSize={15}>{props.text}</MyText>
        </View>
    )
};

class Page extends React.Component<UserProfilePage, any> {
    static defaultProps = {
        canEdit: false,
        createdType: 'edit'
    };

    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            top: new Animated.Value(-SCREEN_WIDTH),
            translucent: true,
        }
    }


    componentDidMount(): void {
        this.props.dispatch({
            type: 'user/isFollow',
            payload: {
                follower: this.props.auth.userInfo.id,
                concerned: this.props.userInfo.id
            }
        });
        this.props.dispatch({
            type: 'user/fetchColleague',
            payload: {
                uid: this.props.userInfo.id,
                cid: this.props.userInfo.company.id
            }
        });
        this.props.dispatch({
            type: 'user/fetchUserInfo',
            payload: {id: this.props.userInfo.id}
        })
    }


    shouldComponentUpdate(nextProps: UserProfilePage, nextState: any, nextContext: any): boolean {

        if (this.state !== nextState) return true;

        if (nextProps.user.info !== this.props.user.info) return true;
        if (nextProps.user.follow !== this.props.user.follow) return true;
        if (nextProps.user.colleague !== this.props.user.colleague) return true;
        return false;
    }

    onFollow = () => {
        this.props.dispatch({
            type: 'user/follow',
            payload: {
                follower: this.props.auth.userInfo.id,
                concerned: this.props.userInfo.id
            }
        })
    };


    //更多操作
    operationPress = () => {
        ActionSheet.showActionSheetWithOptions({
                options: ['静音通知', '举报', '取消',],
                cancelButtonIndex: 2,
                destructiveButtonIndex: 1,
                maskClosable: true,
            },
            (buttonIndex) => {
            });
    };
    renderAvatar = () => {
        const user: userItem = this.props.user.info;
        return (
            <View style={[commonStyles.flex1, commonStyles.centerVH]}>
                <Avatar size={autoSize(170)}
                        source={{uri: Request.checkImageUrl(user.avatar) + ''}}/>
            </View>
        );
        // return (
        //     <View style={[commonStyles.flex1, commonStyles.centerVH]}>
        //         <MyIcon name='icon-addpicture' size={30} color='#C3C2C2'/>
        //         <MyText style={{
        //             backgroundColor: 'transparent',
        //             marginTop: 5,
        //             color: '#666666',
        //             fontSize: 14
        //         }}>添加档案图片</MyText>
        //     </View>
        // )
    };
    renderIntroduce = () => {
        const user: userItem = this.props.user.info;


        let skillItems = [];
        let hobbies = [];


        if (user.skill) {
            skillItems = user.skill.map((s: skillItem, index) => {
                return (
                    <View style={[commonStyles.centerVH, {
                        backgroundColor: 'blue', padding: 5, borderRadius: 11,
                        marginTop: 5
                    }]} key={index}>
                        <MyText color={Colors.White} fontSize={12}>{s.text}</MyText>
                    </View>
                )
            });
        }

        if (user.hobby) {
            hobbies = user.hobby.map((s: hobbyItem, index) => {
                return (
                    <View style={[commonStyles.centerVH, {
                        backgroundColor: 'blue', padding: 5, borderRadius: 11,
                        marginTop: 5
                    }]} key={index}>
                        <MyText color={Colors.White} fontSize={12}>{s.text}</MyText>
                    </View>
                )
            })
        }


        return (
            <View>
                <Title text='关于我' key={0}/>
                <View style={[commonStyles.flexColumn, {alignItems: 'center', padding: 15}]} key={1}>
                    <MyText style={{textAlign: 'center'}}>
                        {user.introduce ? user.introduce : ''}
                    </MyText>
                    {user.skill && user.skill.length > 0 ? <MyText style={{marginVertical: 15}}>我的技能</MyText> : null}
                    {skillItems}
                    {user.hobby && user.hobby.length > 0 ? <MyText style={{marginVertical: 15}}>我的兴趣</MyText> : null}
                    {hobbies}
                </View>
            </View>
        )

        //
        // let views = [];
        // views.push(<Title text='关于我' key={0}/>);
        // views.push();

        // return views;
    };

    renderDynamicHeader = () => {
        const follow = this.props.user.follow;
        const user: userItem = this.props.user.info;

        if (!user) return null;


        return (
            <View style={{backgroundColor: Colors.White}}>

                {/*头像*/}
                <View style={archiveStyles.headerView}>
                    <View style={archiveStyles.avatarContainer} activeOpacity={1}>
                        <View style={archiveStyles.avatar}>
                            {this.renderAvatar()}
                        </View>
                    </View>
                    <View style={archiveStyles.headerBottom}/>
                </View>

                {/*基本信息*/}
                <View style={[commonStyles.flexColumn, {alignItems: 'center'}]}>
                    <MyText style={{padding: 5}} fontSize={14}>{user.nickName}</MyText>

                    <MyText style={{padding: 5}} fontSize={12} color={Colors.Brief}
                            numberOfLines={0}>{`${user.duty ? user.duty + 'at' : ''}  ${user.company.name}`}}</MyText>
                    <MyText style={{padding: 5}} fontSize={12} color={Colors.Brief}
                            numberOfLines={1}>{user.company.area.name}</MyText>

                    <MyText color={Colors.Active}
                            style={{padding: 5}}>{`${follow.followers}个关注者`}</MyText>
                </View>

                {/*操作*/}
                {this.props.user.info.account !== this.props.auth.userInfo.account ?
                    <View style={[commonStyles.flexRow, {padding: 5, height: autoSize(50)}]}>
                        <TouchableOpacity onPress={this.onFollow}
                                          style={[commonStyles.flex1, commonStyles.centerVH, userProfileStyle.followBtn, follow.isFollow ? userProfileStyle.disabled : null]}>
                            <MyIcon name={follow.isFollow ? 'icon-gou' : 'icon-jia1'}
                                    color={follow.isFollow ? Colors.Border : Colors.White}/>
                            <MyText
                                color={follow.isFollow ? Colors.Border : Colors.White}
                                style={{marginLeft: 5}}>{follow.isFollow ? '已关注' : '关注'}</MyText>
                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={Actions.chat.bind(this, {
                                title: this.props.user.info.nickName,
                                receiver: this.props.user.info.account
                            })}
                            style={[commonStyles.flex1, commonStyles.centerVH, {backgroundColor: Colors.Active}]}>
                            <MyText color={Colors.White}>消息</MyText>
                        </TouchableOpacity>
                    </View> : null}

                <WhiteSpace color={Colors.Background}/>


                {this.renderIntroduce()}
                <WhiteSpace color={Colors.Background}/>

                {/*我工作的地点在 标题*/}
                <Title text='我工作的地点在'/>

                {/*工作地点*/}
                <View style={[commonStyles.flexRow]}>
                    <Avatar source={{uri: Request.checkImageUrl(user.company.pic)}} circle={false} size={autoSize(90)}/>
                    <View style={[commonStyles.flex1, {justifyContent: 'center', marginLeft: 15}]}>
                        <MyText>{user.company.name}</MyText>
                        <MyText>{user.company.address}</MyText>
                    </View>
                </View>

                {/*我的同事 标题*/}
                <Title text='我的同事'/>
                {/*我的同事*/}
                <View style={[commonStyles.flexRow]}>
                    {this.props.user.colleague.map((userInfo: userItem, index) => {
                        if (index > 4) return null;
                        if (index === 4) {
                            return (
                                <View style={[commonStyles.centerVH, {
                                    width: autoSize(SCREEN_WIDTH / 5),
                                    height: autoSize(SCREEN_WIDTH / 5)
                                }]} key={index}>
                                    <Avatar size={autoSize(SCREEN_WIDTH / 5 * 0.6)}
                                            content={'更多'}
                                            onPress={Actions.colleagueList}/>
                                </View>
                            )
                        }
                        return (
                            <View style={[commonStyles.centerVH, {
                                width: autoSize(SCREEN_WIDTH / 5),
                                height: autoSize(SCREEN_WIDTH / 5),

                            }]} key={index}>
                                <Avatar source={{uri: Request.checkImageUrl(userInfo.avatar) + ''}}
                                        size={autoSize(SCREEN_WIDTH / 5 * 0.6)}
                                        borderColor={Colors.Border}
                                        borderWidth={1}
                                        onPress={Actions.userProfile.bind(null, {userInfo})}
                                />
                            </View>
                        )
                    })}
                </View>

                <WhiteSpace color={Colors.Background}/>
                {/*联系 标题*/}
                <Title text='联系'/>

                {/*联系*/}
                {user.website ? <View>
                    <View style={{padding: 8, borderBottomWidth: 0.5, borderBottomColor: Colors.Background}}>
                        <MyText>website</MyText>
                        <MyText>{user.website}</MyText>
                    </View>
                    {/*{contactList.map((item, index) => (*/}
                    {/*))}*/}
                </View> : null}
                <WhiteSpace color={Colors.Background}/>
                {/*推送和社区 标题*/}
                <Title text='推送和社区'/>

            </View>
        )
    };

    renderRightButton = () => {
        if (this.props.canEdit) {
            return (
                <NavRightButton icon={{name: 'icon-qianbi', color: 'white'}}
                                onPress={Actions.createArchives.bind(this, {
                                    createdType: this.props.createdType,
                                    userInfo: this.props.user.info
                                })}/>
            )
        } else {
            return (
                <NavRightButton onPress={this.operationPress}>
                    <MyText color={Colors.White} fontSize={20}>⋅⋅⋅</MyText>
                </NavRightButton>
            )
        }
    };

    onScroll = (e) => {
        // console.log(e.nativeEvent.contentOffset);
        Animated.timing(
            this.state.top, {
                toValue: -SCREEN_WIDTH - e.nativeEvent.contentOffset.y,
                duration: 0
            }
        ).start();

        if (e.nativeEvent.contentOffset.y > 100) {
            this.setState({
                translucent: false
            })
        } else {
            this.setState({
                translucent: true
            })
        }

    };

    render() {
        const user: userItem = this.props.user.info;

        return (
            <View
                style={[commonStyles.container, commonStyles.relative, {zIndex: 222}]}>
                <View style={{zIndex: 999999}}>
                    <NavigationBar {...commonProps.navBar}
                                   style={{
                                       backgroundColor: this.state.translucent ? 'transparent' : Colors.Primary,
                                       zIndex: 444
                                   }}
                                   tintColor={this.state.translucent ? 'transparent' : Colors.Primary}
                                   leftButton={<NavBackButton/>}
                                   rightButton={this.renderRightButton()}
                                   title={{
                                       title: this.state.translucent ? '' : user ? user.nickName : '',
                                       tintColor: Colors.White
                                   }}
                    />
                </View>
                <View style={[commonStyles.flex1, commonStyles.absolute, {zIndex: 111, height: SCREEN_HEIGHT}]}>
                    <FlatList data={homeDynamicList}
                              onScroll={this.onScroll}
                              scrollEventThrottle={50}
                              style={{zIndex: 111}}
                              renderItem={({item}) => <DynamicItem {...item}
                                                                   onCommentPress={Actions.postingsDetail.bind(null, {dynamicItem: item})}
                                                                   onUserInfoPress={Actions.postingsDetail.bind(null, {dynamicItem: item})}/>}
                              ListHeaderComponent={this.renderDynamicHeader}
                              keyboardDismissMode='on-drag'
                              keyExtractor={(item, index) => index}
                              extraData={this.state}
                              ItemSeparatorComponent={() => <WhiteSpace color={Colors.Background}/>}
                    />
                    <Animated.View style={[commonStyles.absolute, {
                        width: SCREEN_WIDTH, height: autoSize(SCREEN_WIDTH),
                        backgroundColor: '#EB7B0A',
                        left: 0,
                        zIndex: -1,
                        top: this.state.top,
                    }]}/>
                </View>


            </View>
        );
    }
}


export default connect(
    ({auth, user}) => ({auth, user})
)(Page);